<template>
  <div class="poster">
    <img
      :src="tempFilePath"
      style="width:100%;height:100%;position:fixed;top:-50px;left:0;z-index:99"
      alt
    />
    <canvas
      v-show="hide"
      canvas-id="mycanvas"
      class="mycanvas"
      :style="{width:screenWidth+'px',height:screenHeight+'px'}"
    />
    <!-- 底部购买 -->
    <div class="footer">
      <button class="btn" @click="tosave">保存图片</button>
      <!-- <button class="btn" v-if="!isAuthSavePhoto" @click="onSaveToPhone ">保存图片</button>
      <button class="btn" v-else @click="showModal">保存图片</button>-->
    </div>
  </div>
</template>

<script>
import { posterDetail } from '@/api/api';
export default {
  data () {
    return {
      isAuthSavePhoto: false,
      rpx: 1,
      hide: true,
      tempFilePath: '',
      screenWidth: '',
      screenHeight: '',
      navHeight: null,
      id: null,
      res: null,
      height: null,
      priceHeigth: 0
    };
  },
  mounted () {
    Object.assign(this.$data, this.$options.data());
    this.id = this.$mp.query.id;
    this.posterDetail();
  },
  methods: {
    async posterDetail () {
      wx.showLoading({
        title: '加载中',
        icon: 'none',
        mask: true
      });
      await posterDetail({ id: this.id }).then(res => {
        this.res = res;
        var fonts2 = `3、您认购的出资金额是人民币${this.res.amount}(￥${
          res.purchaseAmount
        });`;
        if (fonts2.length > 30) {
          this.priceHeigth = 20;
        } else {
          this.priceHeigth = 0;
        }
        this.createNewImg();
      });
    },
    /** 换行 */
    async lineFend (txt, context, height) {
      var text = txt;
      var chr = text.split(''); // 这个方法是将一个字符串分割成字符串数组
      var temp = '';
      var row = [];
      context.setFontSize(11 * this.rpx);
      context.setFillStyle('#000');
      for (var a = 0; a < chr.length; a++) {
        if (context.measureText(temp).width < 300) {
          temp += chr[a];
        } else {
          a--; // 这里添加了a-- 是为了防止字符丢失，效果图中有对比
          row.push(temp);
          temp = '';
        }
      }
      row.push(temp);
      // 如果数组长度大于2 则截取前两个
      if (row.length > 2) {
        var rowCut = row.slice(0, 2);
        var rowPart = rowCut[1];
        var test = '';
        var empty = [];
        for (let a = 0; a < rowPart.length; a++) {
          if (context.measureText(test).width < 280) {
            test += rowPart[a];
          } else {
            break;
          }
        }
        empty.push(test);
        var group = empty[0] + '...'; // 这里只显示两行，超出的用...表示
        rowCut.splice(1, 1, group);
        row = rowCut;
      }
      for (let b = 0; b < row.length; b++) {
        context.fillText(
          row[b],
          50 * this.rpx,
          (height + b * 20) * this.rpx,
          280 * this.rpx
        );
      }
    },
    // 将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
    createNewImg: function () {
      /** 获取屏幕额宽高 */
      let menuButtonObject = wx.getMenuButtonBoundingClientRect();
      console.log(menuButtonObject, 'menuButtonObjectmenuButtonObject');
      wx.getSystemInfo({
        success: res => {
          this.rpx = res.windowWidth / 375;
          let statusBarHeight = res.statusBarHeight;
          this.navHeight =
            statusBarHeight +
            menuButtonObject.height +
            (menuButtonObject.top - statusBarHeight) * 2; // 导航高度
          this.screenWidth = res.screenWidth;
          this.screenHeight = res.screenHeight - this.navHeight;
        }
      });

      var context = wx.createCanvasContext('mycanvas');
      context.setFillStyle('#fff');
      context.fillRect(0, 0, this.screenWidth, this.screenHeight);

      wx.downloadFile({
        url: this.res.picImg,
        success: res => {
          console.log(res);
          var imgUrl = res.tempFilePath;
          wx.getImageInfo({
            src: imgUrl,
            success: item => {
              console.log(item);
              console.log(this.screenWidth, this.screenHeight);
              this.height =
                (this.screenHeight -
                  this.screenWidth * item.height / item.width) /
                2;
              this.canvasHeight = this.screenWidth * item.height / item.width;
              context.drawImage(
                imgUrl,
                0,
                this.height,
                this.screenWidth,
                this.screenWidth * item.height / item.width
              );

              // 绘制标语
              context.setFontSize(11 * this.rpx);
              context.setFillStyle('#000');
              context.setTextAlign('left');
              context.fillText(
                `尊敬的投资人:${this.res.customerName} `,
                50 * this.rpx,
                (180 + this.height) * this.rpx
              );
              context.stroke();

              context.setFontSize(11 * this.rpx);
              context.setFillStyle('#000');
              context.setTextAlign('left');
              context.fillText(
                `您好`,
                50 * this.rpx,
                (200 + this.height) * this.rpx
              );
              context.stroke();

              context.setFontSize(11 * this.rpx);
              context.setFillStyle('#000');
              var fonts1 = `感谢认购“${this.res.productName}”`;
              this.lineFend(fonts1, context, 220 + this.height);
              context.stroke();

              context.setFontSize(11 * this.rpx);
              context.setFillStyle('#000');
              context.setTextAlign('left');
              context.fillText(
                '本认购确认书如下:',
                50 * this.rpx,
                (250 + this.height) * this.rpx
              );
              context.stroke();

              context.setFontSize(11 * this.rpx);
              context.setFillStyle('#000');
              context.setTextAlign('left');
              // context.fillText(
              //   `1、客户姓名:${this.res.customerName}（证件号码:${this.res.certificateNumber}）`,
              //   50 * this.rpx,
              //   320 * this.rpx
              // );
              var name1 = `1、客户姓名:${this.res.customerName}（证件号码:${
                this.res.certificateNumber
              }）`;
              this.lineFend(name1, context, 270 + this.height);
              context.stroke();

              context.setFontSize(11 * this.rpx);
              context.setFillStyle('#000');
              context.setTextAlign('left');
              var name2 = `2、本产品募集期间为:${
                this.res.raisingStartData ? this.res.raisingStartData : '-'
              }~${this.res.interestDay ? this.res.interestDay : '-'}`;
              this.lineFend(name2, context, 290 + this.height);
              context.stroke();

              context.setFontSize(11 * this.rpx);
              context.setFillStyle('#000');
              context.setTextAlign('left');
              var fonts2 = `3、您认购的出资金额是人民币${
                this.res.purchaseAmount
              }（￥${this.res.amount}）;`;
              this.lineFend(fonts2, context, 310 + this.height);
              context.stroke();

              context.setFontSize(11 * this.rpx);
              context.setFillStyle('#000');
              context.setTextAlign('left');
              context.fillText(
                `4、投资期限:提取产品期限:${this.res.raisingPeriod}个月。`,
                50 * this.rpx,
                (330 + this.height + this.priceHeigth) * this.rpx
              );
              context.stroke();

              context.setFontSize(11 * this.rpx);
              context.setFillStyle('#000');
              context.setTextAlign('left');
              var fonts3 = `5、本产品于${
                this.res.interestDay ? this.res.interestDay : '—'
              }正式放款，同时自该日起计息。`;
              this.lineFend(
                fonts3,
                context,
                350 + this.height + this.priceHeigth
              );
              context.stroke();
              context.setFontSize(11 * this.rpx);
              context.setFillStyle('#000');
              context.setTextAlign('left');
              context.fillText(
                '特此函告。',
                50 * this.rpx,
                (370 + this.height + this.priceHeigth) * this.rpx
              );
              context.stroke();

              //   context.setFontSize(11 * this.rpx);
              //   context.setFillStyle('#000');
              //   context.setTextAlign('left');
              //   context.fillText(
              //     '青岛城世基金管理有限公司',
              //     200 * this.rpx,
              //     520 * this.rpx
              //   );
              //   context.stroke();
              var that = this;
              context.draw(
                true,
                setTimeout(function () {
                  // 将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
                  wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    fileType: 'jpg',
                    quality: 0.8,
                    canvasId: 'mycanvas',
                    success: function (res) {
                      // var tempFilePath = res.tempFilePath;
                      wx.hideLoading();
                      that.tempFilePath = res.tempFilePath;
                      that.hide = false;
                    },
                    fail: function (res) {
                      console.log(res);
                    }
                  });
                }, 200)
              );
            },
            fail: function (fres) {}
          });
        }
      });
    },
    /*
   * 保存到相册
  */
    // 重新保存图片
    tosave: function () {
      var that = this;
      /** 检测用户是否授权**/
      wx.getSetting({
        success: function (res) {
          /** 授权，则调用相册**/
          if (res.authSetting['scope.writePhotosAlbum'] === true) {
            that.saveimg();
          } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
            /** 未授权，则打开授权页面，让用户授权**/
            wx.openSetting({
              success: res => {
                /** 授权成功，则保存图片，失败则不保存**/
                if (res.authSetting['scope.writePhotosAlbum'] === true) {
                  that.saveimg();
                }
              }
            });
          } else {
            that.saveimg();
          }
        },
        fail: function (res) {
          console.log('打开设置失败', res);
        }
      });
    },
    // 保存图片到相册
    saveimg: function () {
      var _that = this;
      wx.saveImageToPhotosAlbum({
        filePath: _that.tempFilePath,
        success (res) {
          wx.showToast({
            title: '已保存到相册'
          });
        },
        fail (res) {}
      });
    },
    // 保存图片到手机
    // 保存图片到手机
    onSaveToPhone () {
      this.getSetting().then(res => {
        // 判断用户是否授权了保存到本地的权限
        if (!res.authSetting['scope.writePhotosAlbum']) {
          this.authorize()
            .then(() => {
              this.savedownloadFile(this.tempFilePath);
              this.isAuthSavePhoto = false;
            })
            .catch(() => {
              wx.showToast({
                title: '您拒绝了授权',
                icon: 'none',
                duration: 1500
              });
              this.isAuthSavePhoto = true;
            });
        } else {
          this.savedownloadFile(this.tempFilePath);
        }
      });
    },
    // 打开设置，引导用户授权
    onOpenSetting () {
      wx.openSetting({
        success: res => {
          console.log(res.authSetting);
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.showToast({
              title: '您未授权',
              icon: 'none',
              duration: 1500
            });
            // 拒绝授权
            this.isAuthSavePhoto = true;
          } else {
            // 接受授权
            this.isAuthSavePhoto = false;
            this.onSaveToPhone(); // 接受授权后保存图片
          }
        }
      });
    },
    // 获取用户已经授予了哪些权限
    getSetting () {
      return new Promise((resolve, reject) => {
        wx.getSetting({
          success: res => {
            resolve(res);
          }
        });
      });
    },
    // 发起首次授权请求
    authorize () {
      return new Promise((resolve, reject) => {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success: () => {
            resolve();
          },
          fail: res => {
            // 这里是用户拒绝授权后的回调
            console.log('拒绝授权');
            // eslint-disable-next-line prefer-promise-reject-errors
            reject();
          }
        });
      });
    },
    savedownloadFile (img) {
      this.downLoadFile(img)
        .then(res => {
          return this.saveImageToPhotosAlbum(res.tempFilePath);
        })
        .then(() => {});
    },
    // 单文件下载(下载文件资源到本地)，客户端直接发起一个 HTTPS GET 请求，返回文件的本地临时路径。
    downLoadFile (img) {
      return new Promise((resolve, reject) => {
        wx.downloadFile({
          url: img,
          success: res => {
            console.log('downloadfile', res);
            resolve(res);
          }
        });
      });
    },
    // 保存图片到系统相册
    saveImageToPhotosAlbum (saveUrl) {
      return new Promise((resolve, reject) => {
        wx.saveImageToPhotosAlbum({
          filePath: saveUrl,
          success: res => {
            wx.showToast({
              title: '保存成功',
              duration: 1000
            });
            resolve();
          }
        });
      });
    },
    // 弹出模态框提示用户是否要去设置页授权
    showModal () {
      wx.showModal({
        title: '检测到您没有打开保存到相册的权限，是否前往设置打开？',
        success: res => {
          if (res.confirm) {
            console.log('用户点击确定');
            this.onOpenSetting(); // 打开设置页面
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.poster {
  // width: 100%;
  // height: 100%;
  // position: fixed;
  // background: url("https://qinghe-zichan.oss-cn-shanghai.aliyuncs.com/qinghe//wGr3C64cnJbZ8BF3dTWfi3RTh6FhbYSjABBp");
  // background-repeat: no-repeat;
  // background-size: 100% 100%;
  .footer {
    z-index: 99;
    height: 54px;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    padding: 6px 15px;
    box-sizing: border-box;
    background-color: #fff;

    .btn {
      line-height: 42px;
      background-color: #187798;
      color: rgba(255, 255, 255, 1);
      font-weight: 700;
      font-size: 15px;
      height: 100%;
    }
  }
  color: #000000;
  font-size: 14px;
  .title {
    padding: 50px 0 30px;
    font-size: 30px;
    color: #43819e;
    text-align: center;
  }
  .sizeColor {
    color: #ff202c;
  }
  .canvas {
    margin-top: 100px;
    width: 200%;
    height: 603px;
    min-height: 300%; // 给200%图片小屏幕会被切掉下面一部分！！！！
    position: fixed;
    top: 99999px;
    left: 0;
  }
}
</style>1